package juc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @program: java-base->CountDownLatchLearn
 * @description:
 * @author: G_Y
 * @create: 2019-08-21 13:43
 **/
public class CountDownLatchLearn {
    static ThreadPoolExecutor threadPoolExecutor =
            new ThreadPoolExecutor(2,4,
                    1, TimeUnit.SECONDS,new ArrayBlockingQueue<>(50),
                    new ThreadPoolExecutor.CallerRunsPolicy());
    public static void main(String[] args) {
        List<Integer> ids = new ArrayList<>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        ids.add(4);
        ids.add(5);
        CountDownLatch countDownLatch = new CountDownLatch(ids.size());
        for (Integer id : ids) {
            final Integer taskId = id;
            threadPoolExecutor.execute(new MyTaskRun(countDownLatch,taskId));
        }
        try {
            // 等待 任务计数器 任务 Down为0 继续往下执行，否则阻塞
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("main over");
    }
}
class MyTaskRun implements Runnable {
    private CountDownLatch countDownLatch;
    private Integer id;

    public MyTaskRun(CountDownLatch countDownLatch, Integer id) {
        this.countDownLatch = countDownLatch;
        this.id = id;
    }

    @Override
    public void run() {
        try {
            System.out.println(id);
            Thread.sleep(100);
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            countDownLatch.countDown();
        }
    }
}

class CountDownTest1 {
    static List<Integer> list =  new ArrayList(100);
    static {
        for (int i = 0; i <100 ; i++) {
            list.add(i);
        }
    }
    static CountDownLatch countDownLatch = new CountDownLatch(100);// 初始化的值跟
    public static void main(String[] args) {
        for (Integer integer : list) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println(integer);
                    }finally {
                        countDownLatch.countDown();// 完成一个任务，做一个减1操作
                    }
                }
            }).start();
        }
        try {
            countDownLatch.await(); // 如果内部的计数值没有到达0，则会对当前线程进行阻塞
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("ALL list Integer is printed");
    }
}
